package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.common.R;
import com.itheima.dto.UserDto;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import com.itheima.util.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserService userService;
    @PostMapping("/login")
    public R<String> login(@RequestBody UserDto userDto,HttpSession session){
//        String code = (String)session.getAttribute(userDto.getPhone());
//        String code = "1234";
        String code = (String) redisTemplate.opsForValue().get(userDto.getPhone());
        String code1 = userDto.getCode();
        if (!code.equals(code1)){
            return R.error("登录失败，验证码错误");
        }
        LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<>();
        qw.eq(User::getPhone,userDto.getPhone());
        User user = userService.getOne(qw);
        if (user==null){
            user = new User();
            user.setName("黑马程序员");
            user.setStatus(1);
            user.setPhone(userDto.getPhone());
            userService.save(user);
        }
        redisTemplate.delete(userDto.getPhone());
        session.setAttribute("user",user.getId());
        return R.success("登录成功");
    }
    @PostMapping("sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpServletRequest request) {
        //获取手机号
        String phone = user.getPhone();
        //生成随机的4位验证码
        String code = ValidateCodeUtils.generateValidateCode(4).toString();
        ////调用阿里云提供的短信服务API完成发送短信
        //SMSUtils.sendMessage("传智健康", "code_1234", phone, code);
        log.info("code={}", code);

        //需要将生成的验证码保存到Session
        redisTemplate.opsForValue().set(phone,"1234",5, TimeUnit.MINUTES);
        return R.success("手机验证码短信发送成功");
    }


}
